#!/usr/bin/python
# -*- coding: UTF-8
import requests
import json
import datetime
import time
import bs4
from lxml import etree



def get_html(url):
    proxies = {"http": "36.25.243.51", "http": "39.137.95.70", "http": "59.56.28.199"}
    headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}
    response = requests.get(url, headers = headers, proxies = proxies)

    return response.text

def get_datas(text):
    soup = bs4.BeautifulSoup(text, "html.parser")

    data = []
    animes = soup.find_all("li", class_= "rank-item")
    
    for anime in animes :
        title = anime.find('div','info').a.string
        link = anime.find('div','info').a['href']
        rank = anime.find('div','num').string
        updata = anime.find('div', 'pgc-info').string
        play = anime.find_all('span', class_='data-box')[0].text
        view = anime.find_all('span', class_='data-box')[1].text
        fav = anime.find_all('span', class_='data-box')[2].text
        data.extend([rank, title, updata, play, view, fav, link])

    return data

def get_bilibili_rank():
    url = "https://www.bilibili.com/v/pget_festival_infoular/rank/bangumi"
    text = get_html(url)
    datas = get_datas(text)
    msg = ""
    i = 0
    for rank, title, updata, play, view, fav, link in slicing(datas, 7):
        msg+=''.join(['排名： ',rank,' 标题： ',title,' 集数： ',updata,' 观看数： ', play,' 评论数: ',view, ' 喜欢数: ', fav, ' 链接 ：',link, '\n'])
        i = i+1
        if i == 10:
            break
    print(msg)
    return msg

def slicing(iterable, n):
      return zip(*[iter(iterable)] * n)    

def add_msg(msg, send_msgs):
    if send_msgs == " ":
        send_msgs = msg
    else:
        send_msgs += "\n" + msg
    return send_msgs
    


def send_msg(content, url):
    """艾特全部，并发送指定信息"""
    data = json.dumps({"msgtype": "text", "text": { "content": content}})
    r = requests.post(url, data, auth=('Content-Type', 'application/json'))
    send_msgs = " "
    print(r.json)


def get_current_time():
    """获取当前时间，当前时分秒"""
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    hour = datetime.datetime.now().strftime("%H")
    mm = datetime.datetime.now().strftime("%M")
    ss = datetime.datetime.now().strftime("%S")
    return now_time, hour, mm, ss


def get_formated_time():
    c_now, c_h, c_m, c_s = get_current_time()
    print("当前时间：", c_now, c_h, c_m, c_s)
    time_msg = "当前时间：" + c_h + ":" + c_m + ":" + c_s
    return time_msg

# 天气获取
def get_weather():
    url = 'http://wthrcdn.etouch.cn/weather_mini?city={}'.format("无锡")
    f = requests.get(url)
    # print(f.text)
    jsons = json.loads(f.text)
    # print(jsons['data']['forecast'])
    date = jsons['data']['forecast'][0]['date']
    weather = jsons['data']['forecast'][0]['type']
    weather_msg = date + "  " + weather
    return weather_msg

# 计算日期
def get_festival_info(y,m,d,jr):
    day = []
    t1 = datetime.datetime.now()#获取当前时间
    t2 = datetime.datetime(int(y),int(m),int(d))#获取指定时间
    t3 = t2 - t1
    #把时间类型转成字符串再分割
    t3 = str(t3).split(',')
    for i in t3:
        day.append(i)
    #取出还有多少天数
    d = day[0]
    if d == "-1 day":
        print("过节了")
    if 'days' not in day[0]:
        print("明天过节")
    elif d > '1 days':
        # print("距离"+jr+"还有%s"%d)
        msg =  ("距离"+jr+"还有 %s"%d)+"\n"
        return msg
    else:
        print("期待明年吧！"+jr)

# 毒鸡汤生成器
def jitang():
    url='https://www.nihaowua.com/home.html'
    res=requests.get(url=url, timeout=10)
    selector = etree.HTML(res.text)
    content = selector.xpath('//section/div/*/text()')[0]
    text = str(content)
    print(text)
    return text

def XiaBan(): 
        # 计算还有多久下班
    now_time_H = int(datetime.datetime.now().strftime('%H'))
    now_time_M = int(datetime.datetime.now().strftime('%M'))

    leave_time_H = 17
    leave_time_M = 30

    msg = ''
    if ((now_time_H < leave_time_H) or ((leave_time_H == now_time_H) and (now_time_M < leave_time_M))):
        min = (leave_time_H - now_time_H) * 60 + leave_time_M - now_time_M
        delta_H = min / 60
        delta_M = min % 60
        msg = ("距离下班还有 %d 小时 %d 分钟")%(delta_H, delta_M)
    else:
        msg = "彦祖，怎么还在加班？"
    return msg

####################################################################################################################
# 摸鱼机器人
def func_I_AM_A_FISH():
    # 标题
    head = "【摸鱼小队】"
    date = datetime.datetime.now().strftime('%p %m-%d %H:%M:%S') + "\n"

    # 鸡汤区
    content = "摸鱼人，工作再累，一定不要忘记摸鱼哦\n有事没事起身去茶水间去厕所去廊道走走，别老在工位上坐着，钱是老板的，但命是自己的\n\n"
    # content = "【毒鸡汤】\n" + jitang() + "\n\n"

    # 今日天气
    url = 'http://wthrcdn.etouch.cn/weather_mini?city={}'.format("无锡")
    f = requests.get(url)
    # print(f.text)
    jsons = json.loads(f.text)
    # print(jsons['data']['forecast'])
    weather = "【天气】" + jsons['data']['forecast'][0]['type'] + "\n"

    # 计算还有几天周末
    year = int(datetime.datetime.now().strftime('%y'))+2000
    day = datetime.datetime.now().strftime('%u')
    day = 5- int(day)
    zm  = "距离周末还有 "+ str(day) +" days\n"
    
    # 计算节假日
    jr1 = get_festival_info(2021,9,21,"中秋节")
    jr2 = get_festival_info(2021,10,1,"国庆节")
    jr3 = get_festival_info(2022,1,1,"元旦节")
    xb = XiaBan()
    msg = head + date + weather + content + zm + jr1 + jr2 + jr3 + xb
    return msg

def send_to_robot(send_msgs, key):
    dict={'jkr':'d423b9e9-6666-4047-bff1-518e221cf445',
    'klxq':'05e263cf-4a2b-4aab-a830-b77744006701'
    };
    url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(dict[key]);
    # 金凯瑞
    # wx_url1 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d423b9e9-6666-4047-bff1-518e221cf445"  
    # 快乐星球
    # wx_url2 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=05e263cf-4a2b-4aab-a830-b77744006701"  
    # send_msgs = add_msg(get_formated_time(), send_msgs)
    # send_msgs = add_msg(get_weather(), send_msgs)
    # send_msgs = add_msg(get_bilibili_rank(), send_msgs)

    send_msgs = add_msg(func_I_AM_A_FISH(), send_msgs)
    # send_msg(send_msgs, wx_url1)
    send_msg(send_msgs, url)


if __name__ == '__main__':
    send_msgs = " "
    # send_msg("@王耀华，狗子，你变了")
    send_to_robot(send_msgs, 'jkr')
